<template>
  <div class="backTop-container" :class="{isShow: isShow}" @click="backToTop">
    <Icon type="md-arrow-round-up" class="back-top" size="24" color="#8590a6"/>
  </div>
</template>
<script>
import {getScrollTop} from '@/common/utils'
export default {
  name: "BackToTop",
  data() {
      return {
          isShow: false
      }
  },
  methods: {
    handleScroll() {
        let scrollTop = getScrollTop()
        if(scrollTop>=400) {
            //当页面滚动到400时，显示回到顶部按钮
            this.isShow = true
        }
        else if(scrollTop<400) {
            this.isShow = false
        }
    },
    backToTop() {
        //点击按钮回到顶部

        //获取此时的滚动高度
        let scrollTop = getScrollTop()
        //每次滚动的距离(1/50)
        let scrollDistance = scrollTop/40
        //当前距离视口的高度
        let currentDistance = scrollTop
        let timer= setInterval( () => {
            currentDistance -= scrollDistance
            if(currentDistance<=0) {
                window.scrollTo(0,0)
                clearInterval(timer)
            }
            window.scrollTo(0,currentDistance)
        },10)
    }
  },
  mounted() {
      window.addEventListener('scroll',this.handleScroll)
  },
};
</script>

<style lang="scss" scoped>
.backTop-container {
  display: none;
  position: fixed;
  bottom: 2rem;
  right: 2rem;
  cursor: pointer;
  width: 4rem;
  height: 4rem;
  line-height: 4rem;
  text-align: center;
  background-color: #fff;
}
.isShow {
    display: block;
}
</style>